<?php
class User_V2_Base 
{
    protected $_uid = 0;
    protected $_userinfo = NULL;

    public function __construct ($uid = 0, $arrUserInfo = NULL)
    {
        $this->_uid = (int) $uid;
        $this->_userinfo = $arrUserInfo;
    }

    public function getUserUid ()
    {
        return Arr::get($this->_userinfo, 'uid', 0);
    }

    public function getUserName ()
    {
        return Arr::get($this->_userinfo, 'userName', '');
    }


    public function getUserIcon ()
    {
        return Arr::get($this->_userinfo, 'userIcon', '');
    }

    public function getUserOpenId ()
    {
        return Arr::get($this->_userinfo, 'userId', '');
    }

    public function getUserGender ()
    {
        return Arr::get($this->_userinfo, 'userGender', 'f');
    }
    
    public function getUserLevel ()
    {
        return Arr::get($this->_userinfo, 'userLevel', '1');
    }

    public function getUserPushId ()
    {
        return Arr::get($this->_userinfo, 'userPushId', '');
    }

    public function getUserType ()
    {
        return Arr::get($this->_userinfo, 'utype');
    }
    
    public function getUserConfigInfo ()
    {
        $uid = $this->getUserUid();
        $query = DB::select()
            ->from('user_v2_userinfo')
            ->where('uid', '=', $uid)
            ->limit(1)
            ->execute()
            ->current();
        
        if(empty($query)){
            return array(
                'userName' => $this->getUserName(),
                'userIcon' => $this->getUserIcon(),
                'userUid'  => $this->getUserUid(),
                'userGender' => $this->getUserGender(),
                'userLevel' => $this->getUserLevel(),
                'userBirthday' => "",
                'userAddress' => "",
                'userComment' => "",
                'userMobile' => "",
            );
        }else{
            return array(
                'userName' => $this->getUserName(),
                'userIcon' => $this->getUserIcon(),
                'userUid'  => $this->getUserUid(),
                'userGender' => $this->getUserGender(),
                'userLevel' => $this->getUserLevel(),
                'userBirthday' => Arr::get($query, 'birthday', ''),
                'userAddress' => Arr::get($query, 'address', ''),
                'userComment' => Arr::get($query, 'comment', ''),
                'userMobile' => Arr::get($query, 'mobile', ''),
            );
        }
    }

    public function getUserInfo ()
    {
        if ($this->_userinfo === NULL && $this->_uid > 0)
        {
            $this->loadUserInfo();
//        foreach($this->_userinfo as $k=>$v){
//        echo $k."=>".$v.";<br>";
//}
//        echo "<hr>";
        }
        
        return array(
            'userName' => $this->getUserName(),
            'userIcon' => $this->getUserIcon(),
            'userUid'  => $this->getUserUid(),
            'userGender' => $this->getUserGender(),
            'userOpenId' => $this->getUserOpenId(),
            'userLevel' => $this->getUserLevel(),
            'userType'  => $this->getUserType(),
        );
    }

    public function logout ()
    {
        if ($this->_uid > 0)
        {
            passport::setCurrentUserUid(0);
        }
    }

    public function setUserIcon ($url)
    {
        if (! preg_match('/^http:\/\//', $url))
        {
            $url = 'http://'.$_SERVER['HTTP_HOST'].$url;
        }

        $rows = DB::update('user_v2')
            ->set(array('userIcon' => $url, 'changed' => DB::expr('unix_timestamp(now())')))
            ->where('uid', '=', $this->_uid)
            ->execute();

        return $rows > 0;
    }

    public function remove ()
    {
        $rows = DB::update('user_v2')
            ->set(array('status' => 99))
            ->where('uid', '=', $this->_uid)
            ->limit(1)
            ->execute();

        return $rows > 0;
    }

    public function incCounts ($type)
    {
        $query = "UPDATE user_v2 set $type=$type+1 WHERE uid=" . $this->_uid;
        $rows = DB::query(Database::UPDATE, $query)->execute();

        return $rows > 0;
    }



    public function updateUserPushId($userPushId)
    {
        if ($this->_uid <= 0)
            return FALSE;

        $origPushId = Arr::get($this->_userinfo, 'userPushId');

        // 注册JChat用户
        $uid      = $this->_uid;
        $nickname = $this->getUserName();
        $gender   = $this->getUserGender();

        $jchat = new JChat;
        $result = $jchat->register(array($uid));
        $result = $jchat->setUserInfo($uid, $nickname, $gender);

 
        $rows = DB::update('user_v2')
            ->set(array('userJChatId' => 'user'.$uid))
            ->where('uid', '=', $uid)
            ->execute();

        /*
        if ($origPushId != $userPushId)
        {
            $rows = DB::update('user_v2')
                ->set(array('userPushId' => $userPushId))
                ->where('uid', '=', $this->_uid)
                ->execute();

            if ($rows > 0)
            {
                // 因为网络响应很慢，所以改成客户端setAlias, 屏蔽从服务器直接setAlias
                //$push = new JPush;
                //$push->setAlias($userPushId, 'u'.$this->_uid);
                $this->_userinfo['userPushId'] = $userPushId;
            }
        }
        */

        return TRUE;
    }

    public function hasLiked ($type, $nid)
    {
        if ($this->_uid == 0)
            return FALSE;
        else
            return $this->hasAction($type, $nid, 'like');
    }

    public function hasAction ($type, $nid, $action = NULL)
    {
        if ($this->_uid == 0)
            return FALSE;

        $count = Data_Base::counts('user_v2_actions', array(
            array('uid', '=', $this->_uid),
            array('type', '=', $type),
            array('nid', '=', $nid),
        ));

        return $count > 0;
    }

    public function addActionShare ($type, $nid)
    {
        if ($this->_uid > 0)
        {
	            $row = array(
	                'uid'  => $this->_uid,
	                'type' => $type,
	                'nid'  => $nid,
                    'action' => 'share',
	                'created' => DB::expr('unix_timestamp(now())'),
	            );
	
	            DB::insert('user_v2_shares')
	                ->columns(array_keys($row))
	                ->values(array_values($row))
	                ->execute();

                $type = 'countsShare';
                $query = "UPDATE user_v2 set $type=$type+1 WHERE uid=" . $this->_uid;
                $rows = DB::query(Database::UPDATE, $query)->execute();

        } // uid > 0
    }

    public function addAction ($type, $nid, $action = NULL, $param1 = NULL, $param2 = NULL)
    {
        if ($this->_uid > 0)
        {
            $count = Data_Base::counts('user_v2_actions', array(
                array('uid', '=', $this->_uid),
                array('type', '=', $type),
                array('nid', '=', $nid),
            ));

            if ($count == 0)
            {
	            $row = array(
	                'uid'  => $this->_uid,
	                'type' => $type,
	                'nid'  => $nid,
	                'action' => $action,
	                'param1' => $param1,
	                'param2' => $param2,
	                'created' => DB::expr('unix_timestamp(now())'),
	            );
	
	            DB::insert('user_v2_actions')
	                ->columns(array_keys($row))
	                ->values(array_values($row))
	                ->execute();

                DB::update('user_v2')
                    ->set(array('countsLike' => DB::expr(`countsLike` + 1)))
                    ->where('uid', '=', $this->_uid)
                    ->execute();
            }
            else
            {
                DB::update('user_v2_actions')
                    ->set(array(
                        'action' => $action,
                        'param1' => $param1,
                        'param2' => $param2,
                        'created' => DB::expr('unix_timestamp(now())'),
                    ))
                    ->where('uid', '=', $this->_uid)
                    ->where('type', '=', $type)
                    ->where('nid', '=', $nid)
                    ->execute();
            }

        } // uid > 0

    }


    public function delAction ($type, $nid)
    {

        $rows = DB::delete('user_v2_actions')
            ->where('uid', '=', $this->_uid)
            ->where('type', '=', $type)
            ->where('nid', '=', $nid)
            ->execute();


        if ($rows > 0)
        {
            try {
            DB::update('user_v2')
            ->set(array('countsLike' => DB::expr('`countsLike` - 1')))
            ->where('uid', '=', $this->_uid)
            ->execute();
            }
            catch (Exception $e)
            {
                //
            }
        }

    } // delAction
    
    public static function  userInfoEdit($arr){
        //更新user_v2表中的，用户名和性别
        try {
            DB::update('user_v2')
            ->set(array('userName' => $arr['userName'], 'userGender' => $arr['userGender']))
            ->where('uid', '=', $arr['userUid'])
            ->execute();
        
            //首先判断该用户是否在user_v2_userinfo表中有记录
            $count = DB::select(array('count("*")', 'count'))
                ->from('user_v2_userinfo')
                ->where('uid', '=', $arr['userUid'])
                ->execute()
                ->get('count');

            if($count > 0){//如果没有则插入
                
                DB::update('user_v2_userinfo')
                    ->set(array('birthday' => $arr['birthday'], 'comment' => $arr['comment'], 'mobile' => $arr['mobile'], 'address' => $arr['address']))
                    ->where('uid', '=', $arr['userUid'])
                    ->execute();
                
            }else{//如果有则更新
                
                $row = array(
                    'uid'      => $arr['userUid'],
                    'birthday' => $arr['birthday'],
                    'comment'  => $arr['comment'],
                    'mobile'   => $arr['mobile'],
                    'address'  => $arr['address'],
                );
	
                DB::insert('user_v2_userinfo')
                    ->columns(array_keys($row))
                    ->values(array_values($row))
                    ->execute();

            }
        }
        catch (Exception $e)
        {
            //
        }
    }

    protected function loadUserInfo ()
    {
        $query = DB::select()
            ->from('user_v2')
            ->where('uid', '=', (int) $this->_uid)
            ->execute();

        if ($query->count() > 0)
        {
            $current = $query->current();
            $uid     = $current['uid'];
            $status  = $current['status'];
            if ($status != 1)
                $this->_userinfo = array();
            else
                $this->_userinfo = $current;
        }
        else
        {
            $this->_userinfo = array();
        }
    }
}
